/*
 * Copyright 2006-2023 ahtelit.com, All Rights Reserved.
 */

package com.telit.firecommand.config.mqtt;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.telit.firecommand.dao.IotDataDAO;
import com.telit.firecommand.dao.IotDeviceDAO;
import com.telit.firecommand.entity.IotData;
import com.telit.firecommand.entity.IotDevice;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;


/**
 * defaultMqttCallBack
 *
 * @author yuezhuang
 * @since 2023-04-28
 */
@Transactional
@Slf4j
@Component("defaultMqttCallBack")
@RequiredArgsConstructor
public class DefaultMqttCallBack extends AbsMqttCallBack {

    private final IotDataDAO iotDataDAO;

    private final IotDeviceDAO iotDeviceDAO;

    @Override
    protected void handleReceiveMessage(String topic, String message) {
        Map<String, Object> messageMap = JSON.parseObject(message, Map.class);
        String data = MapUtil.getStr(messageMap, "data");
        Map<String, Object> dataMap = JSON.parseObject(data, Map.class);
        String sn = MapUtil.getStr(dataMap, "sn");
        LambdaQueryWrapper<IotDevice> iotDeviceLambdaQueryWrapper = new LambdaQueryWrapper<>();
        iotDeviceLambdaQueryWrapper.eq(IotDevice::getSn, sn);
        IotDevice iotDevice = iotDeviceDAO.selectOne(iotDeviceLambdaQueryWrapper);
        if (iotDevice == null) {
            return;
        }

        //保存设备数据
        String messageType = MapUtil.getStr(messageMap, "messageType");
        String msgId = MapUtil.getStr(messageMap, "msgId");
        String timestamp = MapUtil.getStr(messageMap, "timestamp");
        String type = MapUtil.getStr(dataMap, "type");
        String category = MapUtil.getStr(dataMap, "category");
        Date now = new Date();
        IotData iotData = IotData.builder()
                .deviceId(iotDevice.getId())
                .sn(sn)
                .data(data)
                .type(type)
                .category(category)
                .msgId(msgId)
                .timestamp(timestamp)
                .messageType(messageType)
                .createdAt(now)
                .updatedAt(now)
                .build();
        iotDataDAO.insert(iotData);

        //更新设备状态
        Boolean networkStatus = MapUtil.getBool(dataMap, "networkStatus");
        String status = MapUtil.getStr(dataMap, "status");
        if (networkStatus != null) {
            iotDevice.setNetworkStatus(networkStatus);
        }
        if (StrUtil.isNotEmpty(status)) {
            iotDevice.setStatus(status);
        }
        iotDeviceDAO.updateById(iotDevice);
    }

}
